package com.key.modules.shiro;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.key.common.base.RespResult;
import com.key.component.jwt.JwtResult;
import com.key.component.jwt.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Author：朕
 * @Package：com.key.modules.shiro
 * @Project：logistics_system
 * @name：OAuth2Filter
 * @Date：2023/3/25 14:10
 * @Filename：OAuth2Filter
 */

/**
 * oauth2过滤器
 */
public class OAuth2Filter extends AuthenticatingFilter {
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        return null;
    }
    //是访问允许
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        /**
         * 如何解决跨域请求中的OPTIONS请求：进行跨域请求的时候，并且请求头中有额外参数，比如token，客户端会先发送一个OPTIONS请求
         来探测后续需要发起的跨域POST请求是否安全可接受所以这个请求就不需要拦截
         判断用户是否已经登录，如果是options的请求则放行，否则进行调用onAccessDenied进行token认证流程
         */
        if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    //在访问被拒绝 true 放行 false不放行
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        //设置响应类型
        response.setContentType("application/json;charset=utf-8");
        if(token == null || "".equals(token)){
            response.getWriter().write(JSONObject.toJSONString(RespResult.error(401,"invalid token",null)));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        JwtResult jwtResult = JwtUtil.validateJwt(token);
        if (jwtResult.isSuccess()){//合法
            OAuth2Token oAuth2Token = new OAuth2Token(token);
            //再次执行认证
            getSubject(request,response).login(oAuth2Token);
            return true;
        }else{//不合法
            if(jwtResult.getErrCode() == 1005){
                response.getWriter().write(JSONObject.toJSONString(RespResult.error(1005,"Token过期",null)));
            }
            if(jwtResult.getErrCode() == 1006){
                response.getWriter().write(JSONObject.toJSONString(RespResult.error(401,"Token不合法",null)));
            }
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            String json = new Gson().toJson(RespResult.error(401,"登录失败"+throwable.getMessage(),null));
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("Authorization");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("Authorization");
        }
        return token;
    }

}
